package com.gitee.mall.ware.listener;

import com.gitee.common.to.mq.OrderTo;
import com.gitee.common.to.mq.StockLockedTo;
import com.gitee.mall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@RabbitListener(queues = "stock.release.stock.queue")
@Component
public class StockReleaseListener {

    @Autowired
    WareSkuService wareSkuService;

    /**
     * 代替分布式事务：
     * 使用延时任务 定时判断订单是否回滚 或这支付取消
     *
     * @param to
     * @param message
     * @param channel
     */
    @RabbitHandler
    public void handleDelayRelease(StockLockedTo to, Message message, Channel channel) {
        try {
            wareSkuService.releaseStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }

    /**
     * 超时未支付 从订单队列中转发来的消息
     */
    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo to, Message message, Channel channel) {
        try {
            wareSkuService.orderCloseRelease(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }


}
